package com.example.myproject.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 *  注解 说明
 *      1.aop注解
 *      2.引入容器
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
    @Pointcut("execution(public * com.example.myproject.controller.*.*(..))")
    public void model(){

    }



    @Before("model()")
    public void before(JoinPoint joinPoint){

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURI());
        //请求类型
        logger.info("method={}",request.getMethod());
        //ip 地址
        logger.info("ip={}",request.getRemoteAddr());
        //类名 和 方法名
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //参数 （但仅显示了第一个参数 思考）
        logger.info("args={}",joinPoint.getArgs());
        //参数个数
        logger.info("args_length={}", joinPoint.getArgs().length);
    }

    /**
     * 在这个controller 访问之前拦截所有请求
     */
/*    @After("model()")
    public  void  after(){
        System.out.println("[Aspect]Im After");
    }*/

    @AfterReturning(returning = "object",pointcut = "model()")
    public void doAfterRrturning(Object object){
        logger.info("Response={}",object.toString());
    }



}
